package com.tianji.advisor;

import cn.hutool.core.map.MapUtil;
import com.tianji.enums.AgentTypeEnum;
import com.tianji.memory.OptimizeChatMemoryRepository;
import org.springframework.ai.chat.client.ChatClientRequest;
import org.springframework.ai.chat.client.ChatClientResponse;
import org.springframework.ai.chat.client.advisor.api.Advisor;
import org.springframework.ai.chat.client.advisor.api.AdvisorChain;
import org.springframework.ai.chat.client.advisor.api.BaseAdvisor;
import org.springframework.ai.chat.memory.ChatMemory;

/**
 * 对话记录优化
 */
public class RecordOptimizationAdvisor implements BaseAdvisor {

    private final OptimizeChatMemoryRepository  repository;

    public RecordOptimizationAdvisor(OptimizeChatMemoryRepository repository) {
        this.repository = repository;
    }



    @Override
    public ChatClientRequest before(ChatClientRequest chatClientRequest, AdvisorChain advisorChain) {
        return chatClientRequest;
    }

    @Override
    public ChatClientResponse after(ChatClientResponse chatClientResponse, AdvisorChain advisorChain) {
        // 获取大模型 响应内容
        String response = chatClientResponse.chatResponse().getResult().getOutput().getText();
        // 判断响应内容 是否是路由智能体返回的 nextAgent 的 名称 如果是则需要优化，否则无需优化
        AgentTypeEnum agentTypeEnum = AgentTypeEnum.agentNameOf(response);
        if (agentTypeEnum != null) {
            String conversationId = MapUtil.getStr(chatClientResponse.context(), ChatMemory.CONVERSATION_ID);
            repository.optimization(conversationId);
        }
        return chatClientResponse;
    }

    @Override
    public int getOrder() {
        return Advisor.DEFAULT_CHAT_MEMORY_PRECEDENCE_ORDER - 100;
    }
}